// @flow
import React, { Component } from 'react'
import styles from './CustomerActions.css'
import { Checkbox } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const CheckboxGroup = Checkbox.Group
import R from 'ramda'
type Props = {
  refreshCustomers: Function,
  data: Object,
  customersPermission: Object
}
type State = {
  CheckboxValue: Array<string>,
  customersPermission: Object
}
class CustomerActions extends Component {
  props: Props
  state: State
  onChange: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      CheckboxValue: [],
      customersPermission: {}
    }
    this.onChange = this.onChange.bind(this)
  }

  componentWillMount () {
    // 判断是否选上
    const { customersPermission, data } = this.props
    const id = data.id
    if (customersPermission[id]) {
      this.setState({
        CheckboxValue: customersPermission[id].permission
      })
    }
  }

  onChange (checkedValues: Array<string>, data: Object) {
    const { customersPermission } = this.state
    // 编辑或删除选中后需选中“查看”
    if (checkedValues.length > 0 && checkedValues.indexOf('readPermission') === -1) {
      checkedValues.push('readPermission')
    }

    const obj = {
      id: data.id,
      name: data.name,
      permission: checkedValues
    }
    const customer = Object.assign({}, customersPermission, {
      [data.id]: obj
    })
    this.setState({
      CheckboxValue: checkedValues,
      customersPermission: customer
    }, () => {
      this.props.refreshCustomers(customer)
    })
  }

  render () {
    const component = this
    const { data } = this.props
    const { CheckboxValue } = this.state
    return (
      <div className={styles['actions']}>
        <CheckboxGroup
          value={CheckboxValue}
          options={[
            { label: '查看', value: 'readPermission' },
            { label: '编辑', value: 'editPermission' },
            { label: '删除', value: 'delPermission' }
          ]} onChange={function (value) { component.onChange(value, data) }} />
      </div>
    )
  }
}

export default CustomerActions
